package com.bootdo.system.service.impl;

import com.bootdo.system.dao.RoleDao;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.domain.RoleDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.LoginService;
import com.bootdo.system.service.RoleService;
import com.bootdo.system.service.UserService;
import com.bootdo.system.service.WhiteListService;
import com.smart.common.utils.IPUtils;
import com.smart.domain.WhiteListDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleService roleService;
    @Autowired
    private WhiteListService whiteListService;
    @Override
    public Boolean checkIp(String username, HttpServletRequest request) throws Exception {
        //判断当前用户权限
        Map<String, Object> map = new HashMap<>();
        map.put("username",username);
        List<UserDO> userDOS  = userDao.list(map);
        if (userDOS.size() > 1){
            throw new Exception();
        }
        if (userDOS.size() == 0){
            throw new Exception();
        }
        UserDO userDO = userDOS.get(0);
        List<RoleDO> roles = roleService.listByUserId(userDO.getUserId());
        int n = 0;
        for (RoleDO roleDO : roles) {
            if ("admin".equals(roleDO.getRoleSign())){
                n++;
            }
        }
        if (n > 0){
            //判断当前IP是否在白名单
            String ip = IPUtils.getIpAddr(request);
            Map<String,Object> ipMap = new HashMap<>();
            ipMap.put("requestKey",username);
            ipMap.put("ip",ip);
            List<WhiteListDO> whiteListDOS = whiteListService.list(ipMap);
            if (whiteListDOS.size() > 0){
                return true;
            }else{
                return false;
            }
        }
        return true;
    }
}
